package cn.lanqiao.active;

import java.util.concurrent.*;

public class ThreadPoolDemo {
    public static void main(String[] args) {
       new ThreadPoolDemo().begin();
    }

    public void begin(){
        Future future = null;
        //获得一个线程池
        ExecutorService service = Executors.newSingleThreadExecutor();
        //使用线程池启动线程MyRunnable
        for (int i = 0; i < 10; i++) {
            service.execute(new MyRunnable());
        }
        //使用线程池启动线程MyCallable -> 获得返回值future
//        for (int i = 0; i < 10; i++) {
//             future = service.submit(new MyCallable());
//            try {
//                System.out.println(future.get());
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
        service.shutdown();
    }

    class MyRunnable implements Runnable {
        @Override
        public void run() {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "执行了任务...");
        }
    }

    class MyCallable implements Callable<Integer>{

        @Override
        public Integer call(){
            System.out.println(Thread.currentThread().getName() + "执行了任务...");
            return (int)(Math.random()*10);
        }
    }
}
